package com.yiruantong.system.service.core.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiruantong.system.domain.core.SysOssConfig;
import com.yiruantong.system.domain.core.bo.SysOssConfigBo;
import com.yiruantong.system.domain.core.vo.SysOssConfigVo;
import com.yiruantong.system.mapper.core.SysOssConfigMapper;
import com.yiruantong.system.service.core.ISysOssConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.yiruantong.common.core.constant.CacheNames;
import com.yiruantong.common.core.constant.TenantConstants;
import com.yiruantong.common.core.enums.base.EnableEnum;
import com.yiruantong.common.core.exception.ServiceException;
import com.yiruantong.common.core.service.ITenantInitService;
import com.yiruantong.common.core.utils.*;
import com.yiruantong.common.json.utils.JsonUtils;
import com.yiruantong.common.mybatis.core.domain.TenantEntity;
import com.yiruantong.common.mybatis.core.page.PageQuery;
import com.yiruantong.common.mybatis.core.page.TableDataInfo;
import com.yiruantong.common.mybatis.core.service.ServiceImplPlus;
import com.yiruantong.common.oss.constant.OssConstant;
import com.yiruantong.common.redis.utils.CacheUtils;
import com.yiruantong.common.redis.utils.RedisUtils;
import com.yiruantong.common.tenant.helper.TenantHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 对象存储配置Service业务层处理
 *
 * @author YiRuanTong
 * @author 孤舟烟雨
 * @date 2021-08-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysOssConfigServiceImpl extends ServiceImplPlus<SysOssConfigMapper, SysOssConfig, SysOssConfigVo, SysOssConfigBo> implements ISysOssConfigService, ITenantInitService {

  private final SysOssConfigMapper baseMapper;

  /**
   * 项目启动时，初始化参数到缓存，加载配置类
   */
  @Override
  public void init() {
    List<SysOssConfig> list = TenantHelper.ignore(() ->
      baseMapper.selectList(
        new LambdaQueryWrapper<SysOssConfig>().orderByAsc(TenantEntity::getTenantId))
    );
    Map<String, List<SysOssConfig>> map = StreamUtils.groupByKey(list, SysOssConfig::getTenantId);
    try {
      for (String tenantId : map.keySet()) {
        TenantHelper.setDynamic(tenantId);
        // 加载OSS初始化配置
        for (SysOssConfig config : map.get(tenantId)) {
          String configKey = config.getConfigKey();
          if (B.isEqual(config.getStatus(), EnableEnum.ENABLE.getId())) {
            RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, configKey);
          }
          CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
        }
      }
    } finally {
      TenantHelper.clearDynamic();
    }
  }

  @Override
  public SysOssConfigVo queryById(Long ossConfigId) {
    return baseMapper.selectVoById(ossConfigId);
  }

  @Override
  public TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery) {
    LambdaQueryWrapper<SysOssConfig> lqw = buildQueryWrapper(bo);
    Page<SysOssConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
    return TableDataInfo.build(result);
  }


  private LambdaQueryWrapper<SysOssConfig> buildQueryWrapper(SysOssConfigBo bo) {
    LambdaQueryWrapper<SysOssConfig> lqw = Wrappers.lambdaQuery();
    lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysOssConfig::getConfigKey, bo.getConfigKey());
    lqw.like(StringUtils.isNotBlank(bo.getBucketName()), SysOssConfig::getBucketName, bo.getBucketName());
    lqw.eq(ObjectUtil.isNotEmpty(bo.getStatus()), SysOssConfig::getStatus, bo.getStatus());
    lqw.orderByAsc(SysOssConfig::getOssConfigId);
    return lqw;
  }

  @Override
  public Boolean insertByBo(SysOssConfigBo bo) {
    SysOssConfig config = MapstructUtils.convert(bo, SysOssConfig.class);
    validEntityBeforeSave(config);
    boolean flag = baseMapper.insert(config) > 0;
    if (flag) {
      CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
    }
    return flag;
  }

  @Override
  public Boolean updateByBo(SysOssConfigBo bo) {
    SysOssConfig config = MapstructUtils.convert(bo, SysOssConfig.class);
    validEntityBeforeSave(config);
    LambdaUpdateWrapper<SysOssConfig> luw = new LambdaUpdateWrapper<>();
    luw.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfig::getPrefix, "");
    luw.set(ObjectUtil.isNull(config.getRegion()), SysOssConfig::getRegion, "");
    luw.set(ObjectUtil.isNull(config.getExt1()), SysOssConfig::getExt1, "");
    luw.set(ObjectUtil.isNull(config.getRemark()), SysOssConfig::getRemark, "");
    luw.eq(SysOssConfig::getOssConfigId, config.getOssConfigId());
    boolean flag = baseMapper.update(config, luw) > 0;
    if (flag) {
      CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
    }
    return flag;
  }

  /**
   * 保存前的数据校验
   */
  @Override
  public boolean validEntityBeforeSave(SysOssConfig entity) {
    if (StringUtils.isNotEmpty(entity.getConfigKey())
      && !checkConfigKeyUnique(entity)) {
      throw new ServiceException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
    }
    return true;
  }

  @Override
  public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
    if (isValid) {
      if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
        throw new ServiceException("系统内置, 不可删除!");
      }
    }
    List<SysOssConfig> list = CollUtil.newArrayList();
    for (Long configId : ids) {
      SysOssConfig config = baseMapper.selectById(configId);
      list.add(config);
    }
    boolean flag = baseMapper.deleteBatchIds(ids) > 0;
    if (flag) {
      list.forEach(sysOssConfig ->
        CacheUtils.evict(CacheNames.SYS_OSS_CONFIG, sysOssConfig.getConfigKey()));
    }
    return flag;
  }

  /**
   * 判断configKey是否唯一
   */
  private boolean checkConfigKeyUnique(SysOssConfig sysOssConfig) {
    long ossConfigId = ObjectUtil.isNull(sysOssConfig.getOssConfigId()) ? -1L : sysOssConfig.getOssConfigId();
    SysOssConfig info = baseMapper.selectOne(new LambdaQueryWrapper<SysOssConfig>()
      .select(SysOssConfig::getOssConfigId, SysOssConfig::getConfigKey)
      .eq(SysOssConfig::getConfigKey, sysOssConfig.getConfigKey()));
    if (ObjectUtil.isNotNull(info) && info.getOssConfigId() != ossConfigId) {
      return false;
    }
    return true;
  }

  /**
   * 启用禁用状态
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int updateOssConfigStatus(SysOssConfigBo bo) {
    SysOssConfig sysOssConfig = MapstructUtils.convert(bo, SysOssConfig.class);
    int row = baseMapper.update(null, new LambdaUpdateWrapper<SysOssConfig>()
      .set(SysOssConfig::getStatus, "1"));
    row += baseMapper.updateById(sysOssConfig);
    if (row > 0) {
      RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, sysOssConfig.getConfigKey());
    }
    return row;
  }

  /**
   * 租户数据拷贝
   *
   * @param fromPackageId  来源套餐ID
   * @param targetTenantId 目标租户ID
   * @param targetUserId   目标用户ID
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void tenantCopy(Long fromPackageId, String targetTenantId, Long targetUserId) {
    TenantHelper.enableIgnore();
    LambdaQueryWrapper<SysOssConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(SysOssConfig::getTenantId, targetTenantId);
    // 判断已经存在值，不允许重复复制
    if (this.exists(lambdaQueryWrapper)) {
      return;
    }

    // 获取拷贝数据源
    String fromTenantId;
    lambdaQueryWrapper = new LambdaQueryWrapper<>();
    if (NumberUtils.equals(fromPackageId, TenantConstants.PACKAGE_ID_1)) {
      fromTenantId = TenantConstants.DEFAULT_TENANT_ID;
    } else {
      fromTenantId = fromPackageId + '-' + TenantConstants.DEFAULT_TENANT_ID;
    }
    lambdaQueryWrapper.eq(SysOssConfig::getTenantId, fromTenantId);
    List<SysOssConfig> regularList = this.list(lambdaQueryWrapper);

    // 目标数据
    List<SysOssConfig> newList = regularList.stream().peek(m -> {
      m.setTenantId(targetTenantId);
      m.setOssConfigId(null);
    }).toList();

    this.saveBatch(newList);

    TenantHelper.disableIgnore();

    ISysOssConfigService ossConfigService = SpringUtils.getBean(ISysOssConfigService.class);
    // 初始化缓存
    ossConfigService.init();
  }
}
